package com.flyu.myThread.PandC;

// 生产者和消费者模型---管程法
public class TestPC1 {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();

        new Productor(synContainer).start();
        new Comsumer(synContainer).start();
    }
}

// 生产者
class Productor extends Thread{
    // 需要容器
    SynContainer synContainer = new SynContainer();

    public Productor(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synContainer.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}

// 消费者
class Comsumer extends Thread{
    // 需要容器
    SynContainer synContainer = new SynContainer();

    public Comsumer(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            Chicken chicken = synContainer.pop();
            System.out.println("消费了--》"+chicken.id+"只鸡");
        }
    }
}

// 产品--chicken
class Chicken{
    int id;
    public Chicken(int id){
        this.id = id;
    }
}

// 缓冲区
class SynContainer{
    // 缓冲区大小
    Chicken[] chickens = new Chicken[10];
    // 目前数量
    int count = 0;
    // 生产者放入产品
    public synchronized void push(Chicken chicken){
        // 如果满了
        if (count==chickens.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 如果没满，加入
        chickens[count] = chicken;
        count++;

        // 通知
        this.notifyAll();
    }

    // 消费者取出产品
    public synchronized Chicken pop(){
        // 如果缓冲区为空
        if (count==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 如果缓冲区有产品
        count--;
        Chicken chicken = chickens[count];

        // 消费完，通知
        this.notifyAll();
        return chicken;
    }
}
